// http方式

let formidable  = require('formidable');
let fs          = require('fs');
let util        = require('../util')
let exec        = require('child_process').exec;


function http(router){
	
	function result(jn){
		return json={
			code:jn.code||1000,
			desc:jn.desc||'成功',
			data:jn.data||''
		}
	}

	// 验证域名来源
	function respone(ctx,json){
		let referer = util.checkReferer(ctx.request.header.referer);
		if(!referer){
			ctx.body = result({
				code:1001,
				desc:'域名来源未通过！'
			});
			return false;
		}else{
			return true;
		}
	};

	router.all('/' ,  async function (ctx, next) {
		ctx.body='http-push 准备好了额！'
	})

	router.post('/api', async function (ctx, next) {

		// 验证域名来源
		let isUrl = await respone(ctx);
		if(!isUrl) return false;

		async function going(){
			return new Promise((resolve, reject)=> {
				let form = new formidable.IncomingForm();
		        form.parse(ctx.req, (err, fields, files) => {

		        	ctx.res.writeHead(200, {'Content-Type': 'application/json;charset=UTF-8'});

		        	if(err){
		        		ctx.body = result({ code:1001, desc:'文件上传报错！' }); 
		        		resolve('1')
		        		return false;	
		        	}

					let base = null
		        	if(fields.pushtype == 'another'){
		        		base = fields.base || '/data/html/'
		        	}else {
			        	if(/^b2c-h5-morningstar.+/.test(fields.base) || /^b2c-h5-hy.+/.test(fields.base) || /^b2c-h5-bd.+/.test(fields.base)){
						}else{
							ctx.body = result({
								code:1001,
								desc:'文件路径必须为 b2c-h5-morningstar || b2c-h5-hy || b2c-h5-bd 开头!'
							});
							return false;
						};
						
						base     = '/data/html/'+fields.base || '/data/html/b2c-h5-morningstar/lp/'
					};

					let to       = base + files.myfiles.name
					let from     = files.myfiles.path

					let isHave=fs.existsSync(base)
					if(!isHave) fs.mkdirSync(base);

		           	let content = fs.readFileSync(from);
			 		if(!content){
			 			ctx.body = result({ code:1001,desc:'服务器读取文件出错！' }); 
			 			resolve('1')
			 			return false;	
			 		};

			 		fs.writeFileSync(to,content);
			 		
			 		ctx.body = result({}); 

		        	exec(`unzip -o ${to} -d ${base}`,(err,out) => {
		                if(err)  util.returnBeiZhu(`解压文件失败！\n ${err}`);
		                exec(`rm -rf ${to}`,(err,out) => {

		                })	
		                util.returnBeiZhu('解压文件成功!');
		            });

		        	resolve('0')

		        });
	        });
        }

        let res = await going();

  	})
}

module.exports=http


